<script lang="ts" setup name="LoginForm">
import  Message from '@/components/message';
import { ref, watch}  from 'vue'
import userStore from '@/store'
import { useRouter } from 'vue-router';
import { useField,useForm } from 'vee-validate'
import { useIntervalFn } from '@vueuse/core'
import { useCoundom } from '@/utils/hooks';
import { accountRule, codeRule, isAgreeRule, mobileRule, passwordRule } from '@/utils/validate';
const { user } = userStore()
const active = ref<'account' | 'mobile'>('account')
const router = useRouter()
const codeRef = ref<HTMLInputElement | null>(null)
const xcode = ref<HTMLInputElement | null>(null)
// 定时器
// const tame = ref(0)
// const isAgree = ref<boolean>(false)
// const form = ref({
//   account: '',
//   password: '',
//   isAgree: false,
// })

const login = async () => {
  // Message({ type: 'success', text: '登录成功', duration: 3000 })
  // Message({
  //   // type: 'error',
  //   // text: '123'
  // })
  //   if (form.value.account === '') {
  //   Message({ type: 'error', text: '用户名或手机号不能为空' })
  //   return
  // }
  // if (form.value.password === '') {
  //   Message({ type: 'error', text: '密码不能为空' })
  //   return
  // }
  // if (!form.value.isAgree) {
  //   Message({ type: 'error', text: '请同意许可' })
  //   return
  // }
  // console.log('通过校验，可以发送请求')
  const res = await validate()
  // console.log(aaa);
 
  // if(aaa.valid) 

 
  if(active.value === 'account'){
    if(res.errors.account || res.errors.password || res.errors.isAgree) return
   await user.login({account:account.value,password:password.value})
    Message.success('登录成功')
  }else{
    //  Message.error(e.Message)
    if(res.errors.mobile || res.errors.code || res.errors.isAgree) return

   await user.mobileLogin({ mobile: mobile.value, code: code.value })
  }
   
Message.success('登录成功!')
  // 跳转到首页
  router.push('/')
  // Message.success('登录成功')
}

const {validate,resetForm} = useForm({
  validationSchema:{
   account: accountRule,
    password: passwordRule,
    isAgree: isAgreeRule,
    mobile: mobileRule,
    code: codeRule
    
  },
  initialValues: {
    mobile: '',
    code: '',
    account: 'xiaotuxian001',
    password: '123456',
    isAgree: true
  }
})


const { tame, start } = useCoundom(59)
const send = async()=>{
 
  // const res = await validateMobile()
  // if(!res.valid) return codeRef.value?.focus()
  // console.log(123);
  
  //  xcode.value?.focus()
  //  try{
  //    await user.sendMobileMsg(mobile.value)
  //    Message.success('获取验证码成功')
  //  }
  //  catch(e:any){
  //    Message.error(e.Message)
  //  }
  // 定时器
  //   if(tame.value > 0) return
  //    tame.value = 30
  // const timer = setInterval(()=>{
  //   tame.value--
  //  if(tame.value === 0){
  //   clearInterval(timer)
  //  }
  // },1000)
   const res = await validateMobile()
  if (!res.valid) return xcode.value?.focus()
  codeRef.value?.focus()

  // 校验通过后开始倒计时
  if (tame.value > 0) return
  start()

  // // 发送验证码
  // // console.log('要发送验证码!')
  // await user.sendSms(mobile.value)
  // Message.success('发送验证码成功')

  // const { tame, start } = useCountDown(60)
  //   if (tame.value > 0) return
  // // console.log('获取验证码')
  // // 单独校验手机号
  // const res = await validMobile()
  // if (!res.valid) {
  //   // 如果没通过，自动获取手机号的焦点
  //   mobileRef.value!.focus()
  //   return
  // }
  // await user.sendMobileMsg(mobile.value)
  // Message.success('获取验证码成功')

  // start()
}
const {value:account,errorMessage:accountMessage} = useField<string>('account')
const {value:password,errorMessage:passwordMessage} = useField<string>('password')
const {value:isAgree,errorMessage:isAgreeMessage} = useField<boolean>('isAgree')
const {value:mobile,errorMessage:mobileMessage,validate:validateMobile} = useField<string>('mobile')
const {value:code,errorMessage:codeMessage} = useField<string>('code')
watch(active, () => resetForm())

  
</script>
<template>
  <div class="account-box">
    <div class="toggle">
      <a @click="active = 'account'" href="javascript:;" v-if="active === 'mobile'">
        <i class="iconfont icon-user"></i> 使用账号登录
      </a>
      <a @click="active = 'mobile'" href="javascript:;" v-else>
        <i class="iconfont icon-msg"></i> 使用短信登录
      </a>
    </div>
    <div class="form">
      <template v-if="active === 'account'">
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <input type="text" v-model="account" placeholder="请输入用户名" />
          </div>
          <div class="error" v-if="accountMessage"><i class="iconfont icon-warning" />{{accountMessage}}</div>
        </div>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-lock"></i>
            <input type="password" v-model="password" placeholder="请输入密码" />
          </div>
          <div class="error" v-if="passwordMessage"><i class="iconfont icon-warning" />{{passwordMessage}}</div>
        </div>
      </template>
      <template v-else>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <input type="text" ref="codeRef" v-model="mobile" placeholder="请输入手机号" />
          </div>
          <div class="error" v-if="mobileMessage"><i class="iconfont icon-warning" />{{mobileMessage}}</div>

        </div>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-code"></i>
            <input ref="xcode"  v-model="code" type="text" placeholder="请输入验证码" />
            <span class="code" @click="send">{{tame === 0? '发送验证码': `${tame}s后发送`}}</span>
          </div>
          <div class="error" v-if="codeMessage"><i class="iconfont icon-warning" />{{codeMessage}}</div>

        </div>
      </template>
      <div class="form-item">
        <div class="agree">
         
          <Xtxcheckbox v-model="isAgree">我已同意</Xtxcheckbox>
          <a href="javascript:;">《隐私条款》</a>
          <span>和</span>
          <a href="javascript:;">《服务条款》</a>
        </div>
          <div class="error" v-if="isAgreeMessage"><i class="iconfont icon-warning" />{{isAgreeMessage}}</div>

      </div>
      <a href="javascript:;" class="btn" @click="login">登录</a>
    </div>
    <div class="action">
      <a
  href="https://graph.qq.com/oauth2.0/authorize?client_id=100556005&amp;response_type=token&amp;scope=all&amp;redirect_uri=http%3A%2F%2Fwww.corho.com%3A8080%2F%23%2Flogin%2Fcallback"
  ><img
    src="https://qzonestyle.gtimg.cn/qzone/vas/opensns/res/img/Connect_logo_7.png"
    alt="QQ登录"
    border="0"
/></a>
      <div class="url">
        <a href="javascript:;">忘记密码</a>
        <a href="javascript:;">免费注册</a>
      </div>
    </div>
  </div>
</template>

<style scoped lang="less">
// 账号容器
.account-box {
  .toggle {
    padding: 15px 40px;
    text-align: right;
    a {
      color: @xtxColor;
      i {
        font-size: 14px;
      }
    }
  }
  .form {
    padding: 0 40px;
    &-item {
      margin-bottom: 28px;
      .input {
        position: relative;
        height: 36px;
        > i {
          width: 34px;
          height: 34px;
          background: #cfcdcd;
          color: #fff;
          position: absolute;
          left: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 18px;
        }
        input {
          padding-left: 44px;
          border: 1px solid #cfcdcd;
          height: 36px;
          line-height: 36px;
          width: 100%;
          &.error {
            border-color: @priceColor;
          }
          &.active,
          &:focus {
            border-color: @xtxColor;
          }
        }
        .code {
          position: absolute;
          right: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 14px;
          background: #f5f5f5;
          color: #666;
          width: 90px;
          height: 34px;
          cursor: pointer;
        }
      }
      > .error {
        position: absolute;
        font-size: 12px;
        line-height: 28px;
        color: @priceColor;
        i {
          font-size: 14px;
          margin-right: 2px;
        }
      }
    }
    .agree {
      a {
        color: #069;
      }
    }
    .btn {
      display: block;
      width: 100%;
      height: 40px;
      color: #fff;
      text-align: center;
      line-height: 40px;
      background: @xtxColor;
      &.disabled {
        background: #cfcdcd;
      }
    }
  }
  .action {
    padding: 20px 40px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    img {
      cursor: pointer;
    }
    .url {
      a {
        color: #999;
        margin-left: 10px;
      }
    }
  }
}
</style>
